import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {ManageService} from '../../manage.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PermissionService} from '../../../../../service/permission.service';
import {sum} from 'ng-zorro-antd/core/util';
// import * as copy from 'copy-to-clipboard';
import {NzCascaderOption} from 'ng-zorro-antd/cascader';
import { Clipboard } from '@angular/cdk/clipboard';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

interface TrackModalData {
  trackModalVisible: boolean;
  trackModalLoading: boolean;
  remark: string; // 跟进内容
  image: string; // 图片地址
  file: any[]; // 文件
  historyList: any[]; // 跟进历史记录
}

interface AfterSaleModal {
  visible: boolean;
  loading: boolean;
  refundPrice: string; // 退款金额
  bearFreight: string; // 我方承担运费
  auditNote: string; // 备注
}

interface CancelOrderModal {
  visible: boolean;
  loading: boolean;
  remark: string; // 备注
}

interface ModifyConsigneeModal {
  visible: boolean;
  loading: boolean;
  username: string;
  tel: string;
  areas: [];
  areasName: string;
  detailAddress: string;
}

@Component({
  selector: 'app-order-detail',
  templateUrl: './order-detail.component.html',
  styleUrls: ['./order-detail.component.scss']
})
export class OrderDetailComponent implements OnInit {
  detailsDatas: any = {}; // 页面详情
  orderId = ''; // 订单id
  orderDetail: any = {
    orderInfo: { // 订单信息
      serial: '',
      status: 0,
      color: 'black',
      stepIndex: 0,
      checkInfo: '',
      stepList: [],
      refundState: 0,
      freeGiftFlag: '0', // 赠送标识：0-非赠品，1-赠品、2-红包兑换
      favorablePrice: 0, // 优惠金额
      texturePrice: 0, // 礼包兑换(对应兑换手机壳价格)
      dzCouponAmount: 0,
      toast: ''
    },
    logisticsTabs: [], // 物流信息
    consigneeInfo: { // 收货人信息
      consignee: '',
      tel: '',
      address: '',
      detailAddress: '',
      districtId: '',
    },
    buyerInfo: { // 买家信息
      userName: '',
      phone: ''
    },
    proceedsInfo: { // 收款信息
      payStatus: '',
      totalPrice: '',
      realPrice: '',
      expressPrice: '',
      payType: '',
      paymentMerchantNo: '',
      payTime: '',
      payOrderNum: '',
    },
    goodsInfo: {
      count: {
        num: 0,
        count: 0,
        discounts: 0,
      },
      expressPrice: '',
      realPrice: '',
      goodsArray: [],
      aiDouAmount: 0
    },
    trackInfo: [],
    refundInfo: {refundPrice: ''},
    rebateJSON: {} // 返利信息
  };
  trackModal: TrackModalData = {
    trackModalVisible: false,
    trackModalLoading: false,
    remark: '', // 跟进内容
    image: '',
    file: [], // 文件
    historyList: [], // 跟进历史记录
  };
  afterSaleModal: AfterSaleModal = {
    visible: false,
    loading: false,
    refundPrice: '',
    bearFreight: '',
    auditNote: '',
  };
  cancelOrderModal: CancelOrderModal = {
    visible: false,
    loading: false,
    remark: '',
  };
  modifyConsigneeModal: ModifyConsigneeModal = {
    visible: false,
    loading: false,
    username: '',
    tel: '',
    areas: [],
    areasName: '',
    detailAddress: '',
  };
  addressArea: any;
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    this.trackModal.file = [file];
    return false;
  };

  // 商家改价 Modal
  isPriceVisible: boolean = false;
  pricesForm!: FormGroup;

  // 标记 | 取消标记 Modal
  isSignVisble: boolean = false;
  signTitle: string = '标记';
  signForm!: FormGroup;

  /** load data async execute by `nzLoadData` method */
  loadData = (node: NzCascaderOption, index: number) => {
    console.log(this.addressArea);
    console.log(this.addressArea.province);
    return new Promise((resolve: any) => {
      // setTimeout(() => {
      if (index < 0) {
        node.children = this.addressArea.province;
      } else if (index === 0) {
        // @ts-ignore
        node.children = this.addressArea.city[node.value];
      } else {
        // @ts-ignore
        node.children = this.addressArea.county[node.value];
        // node.children = scenicspots[node.value];
      }
      resolve();
// }, 1000);
    });
  };

  constructor(
    private activatedRoute: ActivatedRoute,
    private manageService: ManageService,
    private nzMessageService: NzMessageService,
    private clipboard: Clipboard,
    public permission: PermissionService,
    private fb: FormBuilder
  ) {
  }

  ngOnInit(): void {
    // 改价
    this.pricesForm = this.fb.group({
      realPrice: ['', [Validators.required]],
      note: [''],
    });
    // 标记
    this.signForm = this.fb.group({
      reason: ['', [Validators.required]],
      remarks: ['']
    })

    this.orderId = this.activatedRoute.snapshot.queryParams.id;
    if (this.orderId) {
      this.initDetail();
    }
  }

  // 复制到剪切板
  copyInfo(content: string) {
    // copy(content);
    this.clipboard.copy(content);
    this.nzMessageService.success('复制成功');
  }

  initDetail() {
    this.manageService.httpGet(`${this.manageService.serviceUrl.orderDetail}/${this.orderId}`, null).then((res: any) => {
      if (res.code === 0) {
        const { orderInfo, goodsInfo, refundInfo, rebateJSON } = res.data || {};
        this.detailsDatas = { orderInfo, goodsInfo, refundInfo, rebateJSON };

        // this.orderDetail.orderInfo = orderInfo || {};
        this.orderDetail.orderInfo.status = res.data.orderInfo.status;
        this.orderDetail.orderInfo.serial = res.data.orderInfo.orderNum;
        this.orderDetail.orderInfo.refundState = res.data.orderInfo.refundState;
        this.orderDetail.orderInfo.freeGiftFlag = res.data.orderInfo.freeGiftFlag;
        this.orderDetail.orderInfo.favorablePrice = res.data.orderInfo.favorablePrice;
        this.orderDetail.orderInfo.texturePrice = res.data.orderInfo.texturePrice;
        this.orderDetail.orderInfo.changePrice = res.data.orderInfo.changePrice || 0;
        this.orderDetail.orderInfo.toast = orderInfo.toast || '';
        this.orderDetail.orderInfo.dzCouponAmount = orderInfo.dzCouponAmount || '';

        // else if ([3].includes(res.data.orderInfo.status)) {
        //   this.orderDetail.orderInfo.stepIndex = 2;
        //   this.orderDetail.orderInfo.color = '#FF9D2A';
        // } else if ([4].includes(res.data.orderInfo.status)) {
        //   this.orderDetail.orderInfo.stepIndex = 2;
        //   this.orderDetail.orderInfo.color = '#F56C6C';
        // }
        // 颜色和当前步骤序号
        if ([2].includes(res.data.orderInfo.status)) {
          this.orderDetail.orderInfo.stepIndex = 1;
          this.orderDetail.orderInfo.color = '#409EFF';
        } else if ([3, 4, 5, 6, 7].includes(res.data.orderInfo.status)) {
          this.orderDetail.orderInfo.stepIndex = 3;
          this.orderDetail.orderInfo.color = '#E6A23C';
        } else if ([8].includes(res.data.orderInfo.status)) {
          this.orderDetail.orderInfo.stepIndex = 3;
          this.orderDetail.orderInfo.color = '#303133';
        } else if ([11, 9].includes(res.data.orderInfo.status)) {
          this.orderDetail.orderInfo.stepIndex = 5;
          this.orderDetail.orderInfo.color = '#67C23A';
        } else if ([10, 12, 16].includes(res.data.orderInfo.status)) {
          this.orderDetail.orderInfo.stepIndex = 1;
          this.orderDetail.orderInfo.color = '#F56C6C';
        }
        // 创建时间
        // if (res.data.orderInfo.createTime) {
        // @ts-ignore
        this.orderDetail.orderInfo.stepList.push({name: '买家下单', detail: res.data.orderInfo.createTime});
        // }
        // 支付时间
        if ([2, 3, 4, 5, 6, 7, 8, 9].includes(res.data.orderInfo.status)) {
          // @ts-ignore
          this.orderDetail.orderInfo.stepList.push({name: '买家付款', detail: res.data.orderInfo?.payTime || ''});
        }
        // 审核时间
        if ([2, 3, 4, 5, 6, 7, 8, 9].includes(res.data.orderInfo.status)) {
          // tslint:disable-next-line
          this.orderDetail.orderInfo.stepList.push({
            // @ts-ignore
            name: res.data.orderInfo.status === 4 ? '审核不通过' : '卖家审核', detail: res.data.orderInfo?.auditTime || ''
          });
        }
        // 发货时间
        if ([2, 3, 5, 6, 7, 8, 9].includes(res.data.orderInfo.status)) {
          // @ts-ignore
          this.orderDetail.orderInfo.stepList.push({name: '卖家发货', detail: res.data.orderInfo?.shipTime || ''});
        }
        // 收货时间
        if ([2, 3, 5, 6, 7, 8, 9].includes(res.data.orderInfo.status)) {
          // @ts-ignore
          this.orderDetail.orderInfo.stepList.push({name: '用户收货', detail: res.data.orderInfo?.receiveTime || ''});
        }
        // 完成时间
        if ([2, 3, 5, 6, 7, 8, 9].includes(res.data.orderInfo.status)) {
          // @ts-ignore
          this.orderDetail.orderInfo.stepList.push({name: '交易完成', detail: res.data.orderInfo?.dealTime || ''});
        }
        // 结束
        if ([10, 11, 12].includes(res.data.orderInfo.status)) {
          // @ts-ignore
          this.orderDetail.orderInfo.stepList.push({name: '交易结束', detail: res.data.orderInfo?.endTime || ''});
        }
        this.orderDetail.consigneeInfo = res.data.receiverInfo;
        this.orderDetail.buyerInfo = res.data.userInfo;
        this.orderDetail.proceedsInfo = res.data.payInfo;
        
        this.orderDetail.goodsInfo = {
          ...res.data.goodsInfo, count: {
            num: 0,
            count: 0,
            discounts: 0,
          }
        };
        // console.log(sum(res.data.goodsInfo.goodsArray.map((item: any) => item.num * 1)));
        // console.log(sum(res.data.goodsInfo.goodsArray.map((item: any) => item.totalPrice * 1)));
        // console.log(sum(res.data.goodsInfo.goodsArray.map((item: any) => item.favorablePrice * 1)));
        this.orderDetail.goodsInfo.count.num = sum(res.data.goodsInfo.goodsArray.map((item: any) => item.num * 1));
        this.orderDetail.goodsInfo.count.count = sum(res.data.goodsInfo.goodsArray.map((item: any) => item.totalPrice * 1));
        this.orderDetail.goodsInfo.count.discounts = sum(res.data.goodsInfo.goodsArray.map((item: any) => item.favorablePrice * 1));

        this.orderDetail.goodsInfo.aiDouAmount = goodsInfo.aiDouAmount;

        this.orderDetail.trackInfo = res.data.follow;
        this.orderDetail.logisticsTabs = res.data.expressArray.map((logistics: any) => {
          return {expressName: logistics.expressName, expressNum: logistics.expressNum, children: JSON.parse(logistics.expressTraces)};
        });

        // 退款信息
        this.orderDetail.refundInfo = refundInfo || {};

        // 返利信息
        this.orderDetail.rebateJSON = rebateJSON || {};
      }
    });
  }

  resetTrackModal() {
    this.trackModal = {
      trackModalVisible: false,
      trackModalLoading: false,
      remark: '', // 跟进内容
      image: '',
      file: [], // 文件
      historyList: [], // 跟进历史记录
    };
  }

  // 显示跟进模态框
  showTrackModal() {
    this.trackModal.trackModalVisible = true;
  }

  // 隐藏跟进模态框 submit true 要提交数据
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.trackModalLoading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.manageService.httpPost(this.manageService.serviceUrl.fileUpload, file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.image = res.data;
          }
        });
      }
      this.manageService.httpPost(this.manageService.serviceUrl.orderTrack, {
        orderId: this.orderId,
        url: this.trackModal.image,
        content: this.trackModal.remark
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.resetTrackModal();
          this.initDetail();
        } else {
          this.trackModal.trackModalLoading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.resetTrackModal();
    }
  }

  resetAfterSaleData() {
    this.afterSaleModal = {
      visible: false,
      loading: false,
      refundPrice: '',
      bearFreight: '',
      auditNote: '',
    };
  }

  // 显示售后退款模态框
  showAfterSaleModal() {
    this.resetAfterSaleData();
    this.afterSaleModal.visible = true;
  }

  // 显示售后退款模态框
  hideAfterSaleModal(submit: boolean) {
    if (submit) {
      if (!this.afterSaleModal.refundPrice) {
        this.nzMessageService.warning('请输入退款金额');
        return;
      }
      // if (this.afterSaleModal.bearFreight === null || this.afterSaleModal.bearFreight === ''
      //   || !this.afterSaleModal.bearFreight.toString().match(/^\d*$/)) {
      //   this.nzMessageService.warning('我方承担运费应为正数');
      //   return;
      // }
      // if (!this.afterSaleModal.auditNote) {
      //   this.nzMessageService.warning('请输入备注');
      //   return;
      // }
      this.afterSaleModal.loading = true;
      this.manageService.httpPost(this.manageService.serviceUrl.orderRefund, {
        orderId: this.orderId,
        refundPrice: this.afterSaleModal.refundPrice,
        bearFreight: this.afterSaleModal.bearFreight,
        auditNote: this.afterSaleModal.auditNote,
      }).then((res: any) => {
        if (res.code === 0) {
          this.initDetail();
          this.nzMessageService.success('操作成功');
          this.resetAfterSaleData();
        } else {
          this.nzMessageService.error(res.message);
        }
      }).finally(() => {
        this.afterSaleModal.loading = false;
      });
      return;
    }
    this.afterSaleModal.visible = false;
  }

  resetCancelOrderModalData() {
    this.cancelOrderModal = {
      visible: false,
      loading: false,
      remark: '',
    };
  }

  showCancelOrderModal() {
    this.resetCancelOrderModalData();
    this.cancelOrderModal.visible = true;
  }

  hideCancelOrderModal(submit: boolean) {
    if (submit) {
      if (!this.cancelOrderModal.remark) {
        this.nzMessageService.warning('请输入备注');
        return;
      }
      this.cancelOrderModal.loading = true;
      this.manageService.httpPost(this.manageService.serviceUrl.orderCancel, {
        orderId: this.orderId,
        content: this.cancelOrderModal.remark,
      }).then((res: any) => {
        if (res.code === 0) {
          this.initDetail();
          this.nzMessageService.success('操作成功');
          this.resetCancelOrderModalData();
        } else {
          this.nzMessageService.error(res.message);
        }
      }).finally(() => {
        this.cancelOrderModal.loading = false;
      });
      return;
    }
    this.cancelOrderModal.visible = false;
  }

  onChanges(values: string[]): void {
    console.log(values);
  }


  resetModifyConsigneeModalData() {
    this.modifyConsigneeModal = {
      visible: false,
      loading: false,
      username: '',
      tel: '',
      areas: [],
      areasName: '',
      detailAddress: '',
    };
  }

  showModifyConsigneeModal() {
    this.resetModifyConsigneeModalData();
    import('../../city').then(m => {
      this.addressArea = m.default;
      this.modifyConsigneeModal.visible = true;
      this.modifyConsigneeModal.username = this.orderDetail.consigneeInfo.consignee;
      this.modifyConsigneeModal.tel = this.orderDetail.consigneeInfo.tel;
      // @ts-ignore
      // tslint:disable-next-line:max-line-length
      this.modifyConsigneeModal.areas = this.orderDetail.consigneeInfo.districtId ? this.orderDetail.consigneeInfo.districtId.split(',').reverse().map(item=>item*1) : [];
      this.modifyConsigneeModal.detailAddress = this.orderDetail.consigneeInfo.detailAddress;
    });
  }

  hideModifyConsigneeModal(submit: boolean) {
    if (submit) {

      if (!this.modifyConsigneeModal.username) {
        this.nzMessageService.warning('请输入收货人姓名');
        return;
      }
      if (!((/^\S.*/).test(this.modifyConsigneeModal.username) && (/.*\S$/).test(this.modifyConsigneeModal.username))) {
        this.nzMessageService.warning('姓名不能以空格开头或结尾');
        return;
      }
      if (!this.modifyConsigneeModal.tel) {
        this.nzMessageService.warning('请输入收货人电话号码');
        return;
      }
      if (!(/^[1][3,4,5,6.7,8,9][0-9]{9}$/).test(this.modifyConsigneeModal.tel)) {
        this.nzMessageService.warning('请输入正确的号码');
        return;
      }
      if (!this.modifyConsigneeModal.areas.length) {
        this.nzMessageService.warning('请选择所在地区');
        return;
      }
      if (!this.modifyConsigneeModal.detailAddress) {
        this.nzMessageService.warning('请输入详细地址');
        return;
      }
      this.cancelOrderModal.loading = true;
      this.manageService.httpPost(this.manageService.serviceUrl.orderModifyAddress, {
        consignee: this.modifyConsigneeModal.username,
        id: this.orderId,
        tel: this.modifyConsigneeModal.tel,
        districtId: this.modifyConsigneeModal.areas[this.modifyConsigneeModal.areas.length - 1],
        address: this.modifyConsigneeModal.detailAddress,
      }).then((res: any) => {
        if (res.code === 0) {
          this.initDetail();
          this.nzMessageService.success('操作成功');
          this.resetModifyConsigneeModalData();
        } else {
          this.nzMessageService.error(res.message);
        }
      }).finally(() => {
        this.modifyConsigneeModal.loading = false;
      });
      return;
    }
    this.modifyConsigneeModal.visible = false;
  }

  /**
   * 改价 Modal
   * ----------------------------------------------------------------
   */
  showPriceModal() {
    this.pricesForm.reset();
    this.pricesForm.patchValue({
      realPrice: '',
      note: '',
    })
    this.isPriceVisible = true;
  }
  handleCancel() {
    this.isPriceVisible = false;
  }
  async submitForm() {
    if (this.pricesForm.valid) {
      let params = {
        ...this.pricesForm.value,
        id: this.orderId
      }
      const res: any = await this.manageService.updatePriceData(params);
      if (res.code == 0) {
        this.nzMessageService.success('改价成功');
        this.isPriceVisible = false;
        this.initDetail();
      } else {
        this.nzMessageService.error(res.message);
      }
    } else {
      Object.values(this.pricesForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 标记 Modal
   * ----------------------------------------------------------------
   */
  showSignModal(num: number) {
    this.signTitle = num == 0 ? '标记' : '取消标记';

    if (num == 1) {
      this.signForm.get('reason')!.clearValidators();
      this.signForm.get('reason')!.markAsPristine();
    } else {
      this.signForm.get('reason')!.setValidators(Validators.required);
      this.signForm.get('reason')!.markAsDirty();
    }
    this.signForm.get('reason')!.updateValueAndValidity();

    this.signForm.reset();
    this.isSignVisble = true;
  }
  signCancel() {
    this.isSignVisble = false;
  }
  async submitSign() {
    if (this.signForm.valid) {
      let params = {
        ...this.signForm.value,
        id: this.orderId,
        type: this.orderDetail.orderInfo?.toast ? 1 : 0 // 0 标记 1取消标记
      }
      
      const res: any = await this.manageService.updateSignData(params);
      if (res.code == 0) {
        this.nzMessageService.success('操作成功');
        this.isSignVisble = false;
        this.initDetail();
      } else {
        this.nzMessageService.error(res.message);
      }
    } else {
      Object.values(this.signForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
